const screenshot = require('screenshot-desktop');
const sharp = require('sharp');

class ScreenshotCapture {
  constructor(config = {}) {
    this.quality = config.quality || 75;
    this.maxWidth = config.maxWidth || 800;
    this.captureDelay = config.captureDelay || 300;
    this.lastScreenshot = null;
    this.currentSlideIndex = 1;
  }

  // 捕获屏幕截图
  async captureSlide() {
    try {
      const startTime = Date.now();

      // 捕获屏幕
      const imgBuffer = await screenshot({ format: 'png' });

      const captureTime = Date.now() - startTime;
      console.log(`截图捕获完成 (耗时: ${captureTime}ms)`);

      return imgBuffer;

    } catch (error) {
      console.error('捕获截图失败:', error);
      return null;
    }
  }

  // 压缩图像
  async compressImage(buffer) {
    try {
      const startTime = Date.now();

      const compressed = await sharp(buffer)
        .resize(this.maxWidth, null, {
          fit: 'inside',
          withoutEnlargement: true
        })
        .jpeg({
          quality: this.quality,
          progressive: true
        })
        .toBuffer();

      const compressTime = Date.now() - startTime;
      const originalSize = (buffer.length / 1024).toFixed(2);
      const compressedSize = (compressed.length / 1024).toFixed(2);
      const ratio = ((1 - compressed.length / buffer.length) * 100).toFixed(1);

      console.log(`图像压缩完成 (${originalSize}KB -> ${compressedSize}KB, 压缩率: ${ratio}%, 耗时: ${compressTime}ms)`);

      return compressed;

    } catch (error) {
      console.error('压缩图像失败:', error);
      return buffer;
    }
  }

  // 转换为Base64
  bufferToBase64(buffer) {
    const base64 = buffer.toString('base64');
    return `data:image/jpeg;base64,${base64}`;
  }

  // 捕获并压缩
  async captureAndCompress() {
    const startTime = Date.now();

    try {
      // 捕获截图
      const imgBuffer = await this.captureSlide();
      
      if (!imgBuffer) {
        // 如果捕获失败，返回上一次的截图
        if (this.lastScreenshot) {
          console.log('使用上一次的截图');
          return this.lastScreenshot;
        }
        return null;
      }

      // 压缩图像
      const compressed = await this.compressImage(imgBuffer);

      // 转换为Base64
      const base64Data = this.bufferToBase64(compressed);

      // 保存为最后一次截图
      this.lastScreenshot = base64Data;

      const totalTime = Date.now() - startTime;
      console.log(`截图处理完成 (总耗时: ${totalTime}ms)`);

      if (totalTime > 500) {
        console.warn(`警告: 截图处理时间超过500ms (${totalTime}ms)`);
      }

      return base64Data;

    } catch (error) {
      console.error('捕获和压缩失败:', error);
      return this.lastScreenshot;
    }
  }

  // 获取当前幻灯片索引
  getCurrentSlideIndex() {
    return this.currentSlideIndex;
  }

  // 设置当前幻灯片索引
  setCurrentSlideIndex(index) {
    this.currentSlideIndex = index;
  }

  // 清除缓存的截图
  clearCache() {
    this.lastScreenshot = null;
  }
}

module.exports = ScreenshotCapture;
